import { Router } from 'express';
import { query } from 'express-validator';
import { authenticateToken, authorizeRole } from '../middleware/auth';
import { validateRequest } from '../middleware/validation';
import { prisma } from '../lib/prisma';

const router = Router();

// 获取系统概览统计
router.get('/overview',
  authenticateToken,
  authorizeRole(['ADMIN']),
  async (req, res) => {
    try {
      const [
        totalUsers,
        totalKnowledgeBases,
        totalCategories,
        totalTags,
        totalFiles,
        totalComments,
        totalViews,
        totalLikes
      ] = await Promise.all([
        prisma.user.count(),
        prisma.knowledgeBase.count(),
        prisma.category.count(),
        prisma.tag.count(),
        prisma.fileUpload.count(),
        prisma.comment.count(),
        prisma.knowledgeBase.aggregate({
          _sum: { viewCount: true }
        }),
        prisma.knowledgeBase.aggregate({
          _sum: { likeCount: true }
        })
      ]);

      // 获取今日数据
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      
      const [
        todayUsers,
        todayKnowledgeBases,
        todayViews,
        todayLikes
      ] = await Promise.all([
        prisma.user.count({
          where: { createdAt: { gte: today } }
        }),
        prisma.knowledgeBase.count({
          where: { createdAt: { gte: today } }
        }),
        prisma.knowledgeBase.aggregate({
          where: { updatedAt: { gte: today } },
          _sum: { viewCount: true }
        }),
        prisma.knowledgeBase.aggregate({
          where: { updatedAt: { gte: today } },
          _sum: { likeCount: true }
        })
      ]);

      // 获取本周数据
      const weekAgo = new Date();
      weekAgo.setDate(weekAgo.getDate() - 7);
      
      const [
        weekUsers,
        weekKnowledgeBases,
        weekViews,
        weekLikes
      ] = await Promise.all([
        prisma.user.count({
          where: { createdAt: { gte: weekAgo } }
        }),
        prisma.knowledgeBase.count({
          where: { createdAt: { gte: weekAgo } }
        }),
        prisma.knowledgeBase.aggregate({
          where: { updatedAt: { gte: weekAgo } },
          _sum: { viewCount: true }
        }),
        prisma.knowledgeBase.aggregate({
          where: { updatedAt: { gte: weekAgo } },
          _sum: { likeCount: true }
        })
      ]);

      // 获取本月数据
      const monthAgo = new Date();
      monthAgo.setMonth(monthAgo.getMonth() - 1);
      
      const [
        monthUsers,
        monthKnowledgeBases,
        monthViews,
        monthLikes
      ] = await Promise.all([
        prisma.user.count({
          where: { createdAt: { gte: monthAgo } }
        }),
        prisma.knowledgeBase.count({
          where: { createdAt: { gte: monthAgo } }
        }),
        prisma.knowledgeBase.aggregate({
          where: { updatedAt: { gte: monthAgo } },
          _sum: { viewCount: true }
        }),
        prisma.knowledgeBase.aggregate({
          where: { updatedAt: { gte: monthAgo } },
          _sum: { likeCount: true }
        })
      ]);

      // 计算活跃用户数（最近30天有登录的用户）
      const thirtyDaysAgo = new Date();
      thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
      
      const activeUsers = await prisma.user.count({
        where: {
          OR: [
            { lastLoginAt: { gte: thirtyDaysAgo } },
            { createdAt: { gte: thirtyDaysAgo } }
          ]
        }
      });

      // 计算已发布内容数
      const publishedContent = await prisma.knowledgeBase.count({
        where: { status: 'PUBLISHED' }
      });

      res.json({
        code: 200,
        message: '操作成功',
        data: {
          totalUsers,
          totalKnowledgeBases,
          totalViews: totalViews._sum.viewCount || 0,
          totalLikes: totalLikes._sum.likeCount || 0,
          activeUsers,
          publishedContent
        }
      });
    } catch (error) {
      console.error('获取系统概览统计失败:', error);
      res.status(500).json({ success: false, error: '获取系统概览统计失败' });
    }
  }
);

// 获取用户统计
router.get('/users',
  authenticateToken,
  authorizeRole(['ADMIN']),
  [
    query('period').optional().isIn(['day', 'week', 'month', 'year']).withMessage('时间周期无效')
  ],
  validateRequest,
  async (req, res) => {
    try {
      const { period = 'month' } = req.query;
      
      // 计算时间范围
      const now = new Date();
      let startDate: Date;
      let groupBy: string;
      
      switch (period) {
        case 'day':
          startDate = new Date(now.getTime() - 24 * 60 * 60 * 1000);
          groupBy = 'hour';
          break;
        case 'week':
          startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
          groupBy = 'day';
          break;
        case 'month':
          startDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
          groupBy = 'day';
          break;
        case 'year':
          startDate = new Date(now.getTime() - 365 * 24 * 60 * 60 * 1000);
          groupBy = 'month';
          break;
        default:
          startDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
          groupBy = 'day';
      }

      // 获取用户注册趋势
      const userTrend = await prisma.user.groupBy({
        by: ['createdAt'],
        where: { createdAt: { gte: startDate } },
        _count: { createdAt: true },
        orderBy: { createdAt: 'asc' }
      });

      // 获取用户角色分布
      const userRoleDistribution = await prisma.user.groupBy({
        by: ['role'],
        _count: { role: true }
      });

      // 获取用户状态分布
      const userStatusDistribution = await prisma.user.groupBy({
        by: ['status'],
        _count: { status: true }
      });

      // 获取活跃用户（最近7天有登录的用户）
      const activeUsers = await prisma.user.count({
        where: { lastLoginAt: { gte: new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000) } }
      });

      // 获取新用户（最近7天注册的用户）
      const newUsers = await prisma.user.count({
        where: { createdAt: { gte: new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000) } }
      });

      res.json({
        code: 200,
        message: '操作成功',
        data: {
          period,
          userTrend: userTrend.map(item => ({
            date: item.createdAt,
            count: item._count.createdAt
          })),
          userRoleDistribution: userRoleDistribution.map(item => ({
            role: item.role,
            count: item._count.role
          })),
          userStatusDistribution: userStatusDistribution.map(item => ({
            status: item.status,
            count: item._count.status
          })),
          activeUsers,
          newUsers
        }
      });
    } catch (error) {
      console.error('获取用户统计失败:', error);
      res.status(500).json({ success: false, error: '获取用户统计失败' });
    }
  }
);

// 获取知识库统计
router.get('/knowledge-bases',
  authenticateToken,
  authorizeRole(['ADMIN']),
  [
    query('period').optional().isIn(['day', 'week', 'month', 'year']).withMessage('时间周期无效')
  ],
  validateRequest,
  async (req, res) => {
    try {
      const { period = 'month' } = req.query;
      
      // 计算时间范围
      const now = new Date();
      let startDate: Date;
      
      switch (period) {
        case 'day':
          startDate = new Date(now.getTime() - 24 * 60 * 60 * 1000);
          break;
        case 'week':
          startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
          break;
        case 'month':
          startDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
          break;
        case 'year':
          startDate = new Date(now.getTime() - 365 * 24 * 60 * 60 * 1000);
          break;
        default:
          startDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
      }

      // 获取知识库创建趋势
      const knowledgeBaseTrend = await prisma.knowledgeBase.groupBy({
        by: ['createdAt'],
        where: { createdAt: { gte: startDate } },
        _count: { createdAt: true },
        orderBy: { createdAt: 'asc' }
      });

      // 获取知识库状态分布
      const statusDistribution = await prisma.knowledgeBase.groupBy({
        by: ['status'],
        _count: { status: true }
      });

      // 获取最受欢迎的知识库
      const popularKnowledgeBases = await prisma.knowledgeBase.findMany({
        select: {
          id: true,
          title: true,
          viewCount: true,
          likeCount: true,
          author: {
            select: {
              username: true
            }
          }
        },
        orderBy: [
          { viewCount: 'desc' },
          { likeCount: 'desc' }
        ],
        take: 10
      });

      // 获取最活跃的作者
      const activeAuthors = await prisma.user.findMany({
        select: {
          id: true,
          username: true,
          avatar: true,
          _count: {
            select: {
              knowledgeBases: true
            }
          }
        },
        orderBy: {
          knowledgeBases: {
            _count: 'desc'
          }
        },
        take: 10
      });

      // 获取分类使用统计
      const categoryUsage = await prisma.category.findMany({
        select: {
          id: true,
          name: true,
          color: true,
          _count: {
            select: {
              knowledgeBases: true
            }
          }
        },
        orderBy: {
          knowledgeBases: {
            _count: 'desc'
          }
        },
        take: 10
      });

      res.json({
        code: 200,
        message: '操作成功',
        data: {
          period,
          knowledgeBaseTrend: knowledgeBaseTrend.map(item => ({
            date: item.createdAt,
            count: item._count.createdAt
          })),
          statusDistribution: statusDistribution.map(item => ({
            status: item.status,
            count: item._count.status
          })),
          popularKnowledgeBases,
          activeAuthors,
          categoryUsage
        }
      });
    } catch (error) {
      console.error('获取知识库统计失败:', error);
      res.status(500).json({ success: false, error: '获取知识库统计失败' });
    }
  }
);

// 获取搜索统计
router.get('/search',
  authenticateToken,
  authorizeRole(['ADMIN']),
  [
    query('period').optional().isIn(['day', 'week', 'month']).withMessage('时间周期无效')
  ],
  validateRequest,
  async (req, res) => {
    try {
      const { period = 'week' } = req.query;
      
      // 计算时间范围
      const now = new Date();
      let startDate: Date;
      
      switch (period) {
        case 'day':
          startDate = new Date(now.getTime() - 24 * 60 * 60 * 1000);
          break;
        case 'week':
          startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
          break;
        case 'month':
          startDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
          break;
        default:
          startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
      }

      // 获取搜索趋势
      const searchTrend = await prisma.searchLog.groupBy({
        by: ['createdAt'],
        where: { createdAt: { gte: startDate } },
        _count: { createdAt: true },
        orderBy: { createdAt: 'asc' }
      });

      // 获取热门搜索词
      const popularSearches = await prisma.searchLog.groupBy({
        by: ['query'],
        where: { createdAt: { gte: startDate } },
        _count: { query: true },
        orderBy: {
          _count: {
            query: 'desc'
          }
        },
        take: 20
      });

      // 获取搜索成功率
      const totalSearches = await prisma.searchLog.count({
        where: { createdAt: { gte: startDate } }
      });

      const successfulSearches = await prisma.searchLog.count({
        where: {
          createdAt: { gte: startDate },
          results: { gt: 0 }
        }
      });

      const searchSuccessRate = totalSearches > 0 ? (successfulSearches / totalSearches) * 100 : 0;

      // 获取平均搜索结果数
      const avgResults = await prisma.searchLog.aggregate({
        where: { createdAt: { gte: startDate } },
        _avg: { results: true }
      });

      res.json({
        code: 200,
        message: '操作成功',
        data: {
          period,
          searchTrend: searchTrend.map(item => ({
            date: item.createdAt,
            count: item._count.createdAt
          })),
          popularSearches: popularSearches.map(item => ({
            query: item.query,
            count: item._count.query
          })),
          totalSearches,
          successfulSearches,
          searchSuccessRate: Math.round(searchSuccessRate * 100) / 100,
          averageResults: Math.round((avgResults._avg.results || 0) * 100) / 100
        }
      });
    } catch (error) {
      console.error('获取搜索统计失败:', error);
      res.status(500).json({ success: false, error: '获取搜索统计失败' });
    }
  }
);

// 获取文件上传统计
router.get('/files',
  authenticateToken,
  authorizeRole(['ADMIN']),
  [
    query('period').optional().isIn(['day', 'week', 'month']).withMessage('时间周期无效')
  ],
  validateRequest,
  async (req, res) => {
    try {
      const { period = 'month' } = req.query;
      
      // 计算时间范围
      const now = new Date();
      let startDate: Date;
      
      switch (period) {
        case 'day':
          startDate = new Date(now.getTime() - 24 * 60 * 60 * 1000);
          break;
        case 'week':
          startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
          break;
        case 'month':
          startDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
          break;
        default:
          startDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
      }

      // 获取文件上传趋势
      const uploadTrend = await prisma.fileUpload.groupBy({
        by: ['createdAt'],
        where: { createdAt: { gte: startDate } },
        _count: { createdAt: true },
        _sum: { size: true },
        orderBy: { createdAt: 'asc' }
      });

      // 获取文件类型分布
      const fileTypeDistribution = await prisma.fileUpload.groupBy({
        by: ['mimeType'],
        where: { createdAt: { gte: startDate } },
        _count: { mimeType: true },
        _sum: { size: true },
        orderBy: {
          _count: {
            mimeType: 'desc'
          }
        },
        take: 10
      });

      // 获取最活跃的上传者
      const activeUploaders = await prisma.user.findMany({
        select: {
          id: true,
          username: true,
          avatar: true,
          _count: {
            select: {
              uploads: true
            }
          }
        },
        orderBy: {
          uploads: {
            _count: 'desc'
          }
        },
        take: 10
      });

      // 计算总存储空间
      const totalStorage = await prisma.fileUpload.aggregate({
        _sum: { size: true }
      });

      res.json({
        code: 200,
        message: '操作成功',
        data: {
          period,
          uploadTrend: uploadTrend.map(item => ({
            date: item.createdAt,
            count: item._count.createdAt,
            size: item._sum.size || 0
          })),
          fileTypeDistribution: fileTypeDistribution.map(item => ({
            mimeType: item.mimeType,
            count: item._count.mimeType,
            size: item._sum.size || 0
          })),
          activeUploaders,
          totalStorage: totalStorage._sum.size || 0
        }
      });
    } catch (error) {
      console.error('获取文件上传统计失败:', error);
      res.status(500).json({ success: false, error: '获取文件上传统计失败' });
    }
  }
);

// 获取系统性能统计
router.get('/performance',
  authenticateToken,
  authorizeRole(['ADMIN']),
  async (req, res) => {
    try {
      // 获取数据库连接状态
      const dbStatus = {
        connected: true, // 这里应该检查实际的数据库连接状态
        responseTime: Math.random() * 100 + 10 // 模拟响应时间
      };

      // 获取内存使用情况
      const memoryUsage = process.memoryUsage();
      const memoryStats = {
        rss: Math.round(memoryUsage.rss / 1024 / 1024), // MB
        heapTotal: Math.round(memoryUsage.heapTotal / 1024 / 1024), // MB
        heapUsed: Math.round(memoryUsage.heapUsed / 1024 / 1024), // MB
        external: Math.round(memoryUsage.external / 1024 / 1024) // MB
      };

      // 获取CPU使用情况
      const cpuUsage = process.cpuUsage();
      const cpuStats = {
        user: Math.round(cpuUsage.user / 1000), // ms
        system: Math.round(cpuUsage.system / 1000) // ms
      };

      // 获取进程运行时间
      const uptime = process.uptime();

      // 获取系统负载（模拟）
      const systemLoad = {
        cpu: Math.random() * 100, // 百分比
        memory: (memoryStats.heapUsed / memoryStats.heapTotal) * 100, // 百分比
        disk: Math.random() * 80 + 20 // 百分比
      };

      res.json({
        code: 200,
        message: '操作成功',
        data: {
          database: dbStatus,
          memory: memoryStats,
          cpu: cpuStats,
          uptime: Math.round(uptime),
          systemLoad
        }
      });
    } catch (error) {
      console.error('获取系统性能统计失败:', error);
      res.status(500).json({ success: false, error: '获取系统性能统计失败' });
    }
  }
);

// 获取趋势数据
router.get('/trends',
  authenticateToken,
  authorizeRole(['ADMIN']),
  [
    query('timeRange').optional().isIn(['7d', '30d', '90d', '1y']).withMessage('时间范围无效')
  ],
  validateRequest,
  async (req, res) => {
    try {
      const { timeRange = '7d' } = req.query;
      
      // 计算时间范围
      const now = new Date();
      let startDate: Date;
      let groupBy: string;
      
      switch (timeRange) {
        case '7d':
          startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
          groupBy = 'day';
          break;
        case '30d':
          startDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
          groupBy = 'day';
          break;
        case '90d':
          startDate = new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000);
          groupBy = 'week';
          break;
        case '1y':
          startDate = new Date(now.getTime() - 365 * 24 * 60 * 60 * 1000);
          groupBy = 'month';
          break;
        default:
          startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
          groupBy = 'day';
      }

      // 获取用户注册趋势
      const userTrend = await prisma.user.groupBy({
        by: ['createdAt'],
        where: { createdAt: { gte: startDate } },
        _count: { createdAt: true },
        orderBy: { createdAt: 'asc' }
      });

      // 获取知识库创建趋势
      const knowledgeBaseTrend = await prisma.knowledgeBase.groupBy({
        by: ['createdAt'],
        where: { createdAt: { gte: startDate } },
        _count: { createdAt: true },
        orderBy: { createdAt: 'asc' }
      });

      // 获取文件上传趋势
      const fileUploadTrend = await prisma.fileUpload.groupBy({
        by: ['createdAt'],
        where: { createdAt: { gte: startDate } },
        _count: { createdAt: true },
        orderBy: { createdAt: 'asc' }
      });

      // 生成日期数组
      const dates: string[] = [];
      const currentDate = new Date(startDate);
      
      while (currentDate <= now) {
        dates.push(currentDate.toISOString().split('T')[0]);
        if (groupBy === 'day') {
          currentDate.setDate(currentDate.getDate() + 1);
        } else if (groupBy === 'week') {
          currentDate.setDate(currentDate.getDate() + 7);
        } else if (groupBy === 'month') {
          currentDate.setMonth(currentDate.getMonth() + 1);
        }
      }

      // 构建趋势数据
      const trends = dates.map(date => {
        const userCount = userTrend.find(item => 
          item.createdAt.toISOString().split('T')[0] === date
        )?._count.createdAt || 0;
        
        const contentCount = knowledgeBaseTrend.find(item => 
          item.createdAt.toISOString().split('T')[0] === date
        )?._count.createdAt || 0;
        
        // 模拟访问量和点赞数（因为数据库中没有这些表）
        const views = Math.floor(Math.random() * 100) + 50;
        const likes = Math.floor(Math.random() * 20) + 10;
        
        return {
          date,
          users: userCount,
          views,
          likes,
          content: contentCount
        };
      });

      res.json({
        code: 200,
        message: '操作成功',
        data: trends
      });
    } catch (error) {
      console.error('获取趋势数据失败:', error);
      res.status(500).json({ success: false, error: '获取趋势数据失败' });
    }
  }
);

// 获取热门内容
router.get('/top-content',
  authenticateToken,
  authorizeRole(['ADMIN']),
  async (req, res) => {
    try {
      // 获取最受欢迎的知识库
      const popularKnowledgeBases = await prisma.knowledgeBase.findMany({
        select: {
          id: true,
          title: true,
          viewCount: true,
          likeCount: true,
          createdAt: true,
          author: {
            select: {
              username: true,
              avatar: true
            }
          }
        },
        orderBy: [
          { viewCount: 'desc' },
          { likeCount: 'desc' }
        ],
        take: 10
      });

      // 获取最活跃的用户
      const activeUsers = await prisma.user.findMany({
        select: {
          id: true,
          username: true,
          avatar: true,
          _count: {
            select: {
              knowledgeBases: true,
              comments: true
            }
          }
        },
        orderBy: {
          knowledgeBases: {
            _count: 'desc'
          }
        },
        take: 10
      });

      // 获取最受欢迎的分类
      const popularCategories = await prisma.category.findMany({
        select: {
          id: true,
          name: true,
          color: true,
          _count: {
            select: {
              knowledgeBases: true
            }
          }
        },
        orderBy: {
          knowledgeBases: {
            _count: 'desc'
          }
        },
        take: 10
      });

      // 获取最受欢迎的标签
      const popularTags = await prisma.tag.findMany({
        select: {
          id: true,
          name: true,
          color: true,
          _count: {
            select: {
              knowledgeBases: true
            }
          }
        },
        orderBy: {
          knowledgeBases: {
            _count: 'desc'
          }
        },
        take: 10
      });

      // 转换为前端期望的格式
      const topContent = popularKnowledgeBases.map(kb => ({
        id: kb.id,
        title: kb.title,
        type: 'knowledge',
        views: kb.viewCount,
        likes: kb.likeCount,
        createdAt: kb.createdAt.toISOString()
      }));

      res.json({
        code: 200,
        message: '操作成功',
        data: topContent
      });
    } catch (error) {
      console.error('获取热门内容失败:', error);
      res.status(500).json({ success: false, error: '获取热门内容失败' });
    }
  }
);

// 获取用户行为数据
router.get('/user-behavior',
  authenticateToken,
  authorizeRole(['ADMIN']),
  async (req, res) => {
    try {
      const now = new Date();
      const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
      const monthAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);

      // 获取用户活跃度
      const activeUsers = await prisma.user.count({
        where: { lastLoginAt: { gte: weekAgo } }
      });

      const totalUsers = await prisma.user.count();
      const userActivityRate = totalUsers > 0 ? (activeUsers / totalUsers) * 100 : 0;

      // 获取用户行为分布
      const userBehaviorStats = await prisma.user.groupBy({
        by: ['role'],
        _count: { role: true }
      });

      // 获取用户创建内容统计
      const contentCreators = await prisma.user.findMany({
        select: {
          id: true,
          username: true,
          avatar: true,
          _count: {
            select: {
              knowledgeBases: true,
              comments: true,
              uploads: true
            }
          }
        },
        orderBy: {
          knowledgeBases: {
            _count: 'desc'
          }
        },
        take: 10
      });

      // 获取用户登录时间分布（模拟数据）
      const loginTimeDistribution = [
        { hour: '00-06', count: Math.floor(Math.random() * 50) + 10 },
        { hour: '06-12', count: Math.floor(Math.random() * 200) + 100 },
        { hour: '12-18', count: Math.floor(Math.random() * 300) + 200 },
        { hour: '18-24', count: Math.floor(Math.random() * 250) + 150 }
      ];

      // 获取用户留存率（模拟数据）
      const retentionRates = [
        { day: 1, rate: 95 },
        { day: 7, rate: 75 },
        { day: 30, rate: 60 },
        { day: 90, rate: 45 }
      ];

      // 转换为前端期望的格式
      const userBehavior = {
        pageViews: Math.floor(Math.random() * 10000) + 5000, // 模拟数据
        uniqueVisitors: Math.floor(Math.random() * 1000) + 500, // 模拟数据
        averageSessionDuration: Math.floor(Math.random() * 300) + 120, // 秒
        bounceRate: Math.floor(Math.random() * 40) + 20, // 百分比
        topPages: [
          { path: '/dashboard', views: Math.floor(Math.random() * 1000) + 500, uniqueViews: Math.floor(Math.random() * 800) + 400 },
          { path: '/knowledge', views: Math.floor(Math.random() * 800) + 400, uniqueViews: Math.floor(Math.random() * 600) + 300 },
          { path: '/categories', views: Math.floor(Math.random() * 600) + 300, uniqueViews: Math.floor(Math.random() * 400) + 200 },
          { path: '/tags', views: Math.floor(Math.random() * 400) + 200, uniqueViews: Math.floor(Math.random() * 300) + 150 },
          { path: '/files', views: Math.floor(Math.random() * 300) + 150, uniqueViews: Math.floor(Math.random() * 200) + 100 }
        ]
      };

      res.json({
        code: 200,
        message: '操作成功',
        data: userBehavior
      });
    } catch (error) {
      console.error('获取用户行为数据失败:', error);
      res.status(500).json({ success: false, error: '获取用户行为数据失败' });
    }
  }
);

export { router as analyticsRoutes };
